package com.example.studentmanagement.controller;

import com.example.studentmanagement.entity.Course;
import com.example.studentmanagement.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 〈功能概述〉<br>
 *
 * @className: CourseController
 * @author: 程序员Mars
 * @date: 2024/12/26 20:25
 */
@Controller
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    /**
     * 显示课程列表
     */
    @GetMapping("/list")
    public String listCourses(Model model) {
        List<Course> courses = courseService.getAllCourses();
        model.addAttribute("courses", courses);
        return "course/course-list";
    }

    /**
     * 跳转到新增课程页面
     */
    @GetMapping("/create")
    public String createCourseForm(Model model) {
        model.addAttribute("course", new Course());
        return "course/course-form";
    }

    /**
     * 跳转到编辑课程页面
     */
    @GetMapping("/edit/{id}")
    public String editCourseForm(@PathVariable("id") Integer id, Model model) {
        Course course = courseService.getCourseById(id);
        model.addAttribute("course", course);
        return "course-form";
    }

    /**
     * 保存或更新课程
     */
    @PostMapping("/save")
    public String saveCourse(@ModelAttribute Course course) {
        if (course.getId() == null) {
            courseService.createCourse(course); // 新增
        } else {
            courseService.updateCourse(course); // 更新
        }
        return "redirect:/course/list";
    }

    /**
     * 删除课程
     */
    @GetMapping("/delete/{id}")
    public String deleteCourse(@PathVariable("id") Integer id) {
        courseService.deleteCourse(id);
        return "redirect:/course/list";
    }

}